<template>
  <div class="info-detail-wrapper">
    <div>
      <div style="padding: 10px 20px" class="flex justify-end" v-if="tagTab.length === 1">
        <q-icon class="iconfont icontubiao-67" style="cursor: pointer;font-size: 12px" @click="unbindEquipment"></q-icon>
      </div>
      <div v-if="tagTab.length === 0"  class="full-width flex justify-center items-center" style="height: 400px" @click="addBindingEquipment">
        <AddIcon title="添加设备" />
      </div>
      <div v-else>
        <div v-for="item in tagTab" :key="item.name" :name="item.name">
          <div class="info-detail-container">
            <q-form class="dialog-content">
              <div style="display: flex;justify-content: space-between">
                <div class="left-container">
                  <img src="../../../../statics/img/gateway.png" alt="" width="160px" height="120px">
                  <div class="flex-center margin-t-20">
                    <q-btn class="btn" unelevated  color="primary" label="驱动升级" @click="driverUpgrade" :loading="submitting"/>
                  </div>
                  <div class="flex-center margin-t-20">
                    <q-btn class="btn" unelevated  color="primary" label="测试连接" @click="testOnline" />
                  </div>
                </div>
                <div>
                  <div class="center-container">
                    <!-- 关联设备信息 -->
                    <AssociateDeviceInformation :form="item.form"/>
                    <!-- 设备配置信息 -->

                    <!-- 网口配置信息 -->
                    <NetworkPortConfigInfo :config-form="item.configForm" v-if="item.form && (item.form.communicationTypeIot.toUpperCase() !== 'IO')"/>
                  </div>
                </div>
                <q-btn unelevated
                       label="编辑"
                       color="primary"
                       @click="editBindingEquipment"
                />
              </div>
            </q-form>
          </div>
        </div>
      </div>
    </div>
    <!-- 新增编辑绑定设备 -->
    <AddEditBindingEquipment :visible="bindingEquipmentDialog"
                             @close="closeBindingEquipmentDialog"
                             :form-data="currentFormData"
                             :numOption="numOption"
                             :boxId="boxId"
                             :productName="detailInfo.productName"
                             :device-num="deviceNum"
                             :controllerType="controllerType"
                             @successSubmit="bindingSuccess"
                             @deviceOffline="bindingOffline"
                             ref="bindingEquipment"
    />

    <NetworkPortConfig :form-data="configForm"
                       :device-id="configDeviceId"
                       :visible="networkPortConfigDialog"
                       @close="closeNetworkPortDialog"
                       @configSuccess="configSuccess"
    />
  </div>
</template>

<script>
import NetworkPortConfigInfo from './network-port-config'
import _ from 'lodash'
import {
  onlineTest,
  TestResp,
  deviceOnlineStatus,
  ethDriveSets,
  subDeviceCollectSets,
  getDeviceCNC
} from '../../../../boot/miot/list'
import { driverUpdate, subDeviceDel, driverVersionCompare } from '../../../../boot/miot/details'
import AddEditBindingEquipment from './add-edit-binding-equipment'
import AssociateDeviceInformation from './associated-device-information'
import NetworkPortConfig from '../list-components/gateway-dialog/network-port-config'
import { Dialog } from 'quasar'
import moment from 'moment'
import { toTime } from 'src/filters/filter'
import AddIcon from '../list-components/gateway-dialog/add-icon'

export default {
  name: 'info-detail',
  components: {
    AddIcon,
    NetworkPortConfigInfo,
    AddEditBindingEquipment,
    AssociateDeviceInformation,
    NetworkPortConfig
  },
  props: {
    boxId: {
      type: String,
      default: ''
    },
    subDevices: {
      type: Array,
      default: () => []
    },
    isOnline: {
      type: Boolean,
      default: false
    },
    detailInfo: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      numOption: [],
      tagValue: '',
      tagTab: [],
      deviceMap: new Map(),
      submitting: false,
      bindingEquipmentDialog: false,
      networkPortConfigDialog: false,
      currentFormData: null,
      adding: true,
      configDeviceId: null,
      controllerType: ''
    }
  },
  watch: {
    subDevices: {
      immediate: true,
      handler: function (val) {
        if (this.tagTab && this.tagTab.length > 0) return
        if (!this.isOnline) return
        if (val && val.length > 0) {
          const result = []
          val.map(item => {
            result.push({
              name: item.assetNumber,
              assetNumber: item.assetNumber,
              form: {
                assetNumber: item.assetNumber,
                deviceTypeIot: item.deviceTypeIot,
                deviceFactoryIot: item.deviceFactoryIot,
                deviceSerialIot: item.deviceSerialIot,
                deviceProtocolIot: item.deviceProtocolIot,
                communicationTypeIot: item.communicationTypeIot
              },
              configForm: {
                collect_cycle: '',
                collect_interval: '',
                collect_ip: '',
                collect_port: null,
                file_ip: '',
                file_port: null,
                file_protocol: null,
                file_dev: '',
                file_box: '',
                file_username: '',
                file_password: '',
                dnc_port: '',
                dnc_protocol: null,
                dnc_username: '',
                dnc_password: ''
              },
              numOptions: [{
                name: item.deviceName,
                label: item.assetNumber,
                value: item.assetNumber
              }]
            })
          })
          this.tagTab = result
          if (this.tagTab.length > 0 && !this.tagValue) {
            this.tagValue = this.tagTab[0].name
          }
        }
      }
    },
    deviceNum: {
      immediate: true,
      handler: async function (val) {
        if (!this.deviceNum) return
        if (!this.isOnline) return
        try {
          await this.checkIsOnline(val)
          if (val && !this.tagTab[this.currentIndex].configForm.collect_ip) {
            try {
              const deviceCollect = await subDeviceCollectSets(this.deviceNum)
              const { data } = await ethDriveSets(this.deviceNum)
              const deviceCollectData = deviceCollect.data
              if (data) {
                this.tagTab[this.currentIndex].configForm.collect_cycle = deviceCollectData.collect_cycle
                this.tagTab[this.currentIndex].configForm.collect_interval = deviceCollectData.collect_interval
                this.tagTab[this.currentIndex].configForm.collect_ip = data.collect_ip
                this.tagTab[this.currentIndex].configForm.collect_port = data.collect_port
                this.tagTab[this.currentIndex].configForm.file_ip = data.file_ip
                this.tagTab[this.currentIndex].configForm.file_port = data.file_port
                this.tagTab[this.currentIndex].configForm.file_protocol = deviceCollectData.file_protocol
                this.tagTab[this.currentIndex].configForm.file_dev = deviceCollectData.file_dev
                this.tagTab[this.currentIndex].configForm.file_box = deviceCollectData.file_box
                this.tagTab[this.currentIndex].configForm.file_username = data.file_username || ''
                this.tagTab[this.currentIndex].configForm.file_password = data.file_password || ''
                this.tagTab[this.currentIndex].configForm.dnc_port = data.dnc_port
                this.tagTab[this.currentIndex].configForm.dnc_protocol = deviceCollectData.DNC_protocol
                this.tagTab[this.currentIndex].configForm.dnc_username = data.dnc_username || ''
                this.tagTab[this.currentIndex].configForm.dnc_password = data.dnc_password || ''
              }
            } catch (e) {
            }
          }
        } catch (e) {
        }
      }
    }
  },
  computed: {
    currentIndex () {
      return this.tagTab.findIndex(item => item.name === this.tagValue)
    },
    deviceNum () {
      if (this.tagTab && this.tagTab[this.currentIndex]) {
        return this.tagTab[this.currentIndex].assetNumber
      }
      return null
    },
    currentForm () {
      if (this.tagTab && this.tagTab[this.currentIndex]) {
        return this.tagTab[this.currentIndex].form
      }
      return null
    },
    currentNumOptions () {
      if (this.tagTab && this.tagTab[this.currentIndex]) {
        return this.tagTab[this.currentIndex].numOptions
      }
      return []
    },
    configForm () {
      if (this.tagTab[this.currentIndex] && this.tagTab[this.currentIndex].configForm) {
        return _.cloneDeep(this.tagTab[this.currentIndex].configForm)
      }
      return null
    }
  },
  created () {
  },
  methods: {
    /**
     * 检测子设备是否在线
     */
    checkIsOnline (val) {
      if (!val) return
      return new Promise((resolve, reject) => {
        deviceOnlineStatus(val).then(res => {
          if (res.data.status === 'ONLINE') {
            resolve()
          } else {
            Dialog.create({
              title: `<p class="dialog-notice-title">
        <i class="iconfont icontubiao-28" ></i> 提示</p>`,
              message: `${val}设备不在线，请检查`,
              html: true,
              ok: {
                unelevated: true,
                label: '确认'
              }
            })
            reject()
          }
        }).catch(() => {
          reject()
        })
      })
    },
    /**
     * 获取设备编号options
     */
    async getDevice () {
      const { data } = await getDeviceCNC()
      this.numOption = data.map(item => {
        return {
          name: item.device_name,
          label: item.device_num,
          value: item.device_num
        }
      })
    },
    /**
     * 添加设备绑定
     */
    addBindingEquipment () {
      this.controllerType = '1'
      // 重新获取numOptions
      this.getDevice()
      this.currentFormData = null
      this.bindingEquipmentDialog = true
      this.adding = true
    },

    /**
     * 编辑设备绑定
     */
    editBindingEquipment () {
      this.numOption = this.currentNumOptions
      this.bindingEquipmentDialog = true
      this.currentFormData = _.cloneDeep(this.currentForm)
      this.adding = false
    },

    /**
     * 设备解绑
     */
    async unbindEquipment () {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要解绑设备吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(async () => {
        const name = this.tagTab[0].name
        const data = await subDeviceDel(this.boxId, name)
        if (data.success) {
          this.tagTab.splice(0, 1)
          this.$emit('operateSuccess')
        }
      })
    },

    /**
     * 驱动升级弹窗
     */
    driverUpgrade () {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要升级吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        this.driverUpgradeConfirm()
      })
    },

    /**
     * 驱动升级执行确认
     */
    async driverUpgradeConfirm () {
      this.submitting = true
      const form = this.currentForm
      const productName = `${form.deviceTypeIot}_${form.deviceFactoryIot}_${form.deviceSerialIot}_${form.deviceProtocolIot}_${form.communicationTypeIot}`

      const params = {
        boxId: this.boxId,
        deviceId: this.deviceNum,
        productName: this.detailInfo.productName,
        softWare: productName,
        type: 'Driver',
        softWareOld: productName
      }
      const params1 = {
        boxId: this.boxId,
        deviceId: this.deviceNum,
        productName: this.detailInfo.productName,
        softWare: productName
      }
      try {
        const data = await driverVersionCompare(params)
        if (data.data && data.data.compareRes === 1) {
          const res = await driverUpdate(params1)
          if (res.data === 0) {
            this.testResultTip('升级命令下发成功')
          } else {
            this.testResultTip('升级命令下发失败')
          }
        } else {
          this.testResultTip('驱动已是最新')
        }
      } catch (e) {
      }

      this.submitting = false
    },

    /**
     * 设备绑定成功
     */
    bindingSuccess (item) {
      this.createSuccess(item)
      this.bindingEquipmentDialog = false
      this.networkPortConfigDialog = true
    },

    /**
     * 盒子子设备创建完成
     */
    createSuccess (item) {
      if (this.adding) {
        this.tagTab.push({
          name: item.assetNumber,
          assetNumber: item.assetNumber,
          form: {
            assetNumber: item.assetNumber,
            deviceTypeIot: item.deviceTypeIot,
            deviceFactoryIot: item.deviceFactoryIot,
            deviceSerialIot: item.deviceSerialIot,
            deviceProtocolIot: item.deviceProtocolIot,
            communicationTypeIot: item.communicationTypeIot
          },
          configForm: {
            collect_cycle: '',
            collect_interval: '',
            collect_ip: '',
            collect_port: null,
            file_ip: '',
            file_port: null,
            file_dev: '',
            file_box: '',
            file_username: '',
            file_password: ''
          },
          numOptions: [{
            name: item.deviceName,
            label: item.assetNumber,
            value: item.assetNumber
          }]
        })
        this.tagValue = item.assetNumber
        this.configDeviceId = item.assetNumber
        this.$emit('operateSuccess')
      } else {
        this.configDeviceId = this.deviceNum
        this.tagTab[this.currentIndex].form.assetNumber = item.assetNumber
        this.tagTab[this.currentIndex].form.deviceTypeIot = item.deviceTypeIot
        this.tagTab[this.currentIndex].form.deviceFactoryIot = item.deviceFactoryIot
        this.tagTab[this.currentIndex].form.deviceSerialIot = item.deviceSerialIot
        this.tagTab[this.currentIndex].form.deviceProtocolIot = item.deviceProtocolIot
        this.tagTab[this.currentIndex].form.communicationTypeIot = item.communicationTypeIot
      }
      this.$refs.bindingEquipment.reset()
    },

    /**
     * 设备绑定离线
     */
    bindingOffline (item) {
      this.createSuccess(item)
    },

    /**
     * 配置成功
     */
    configSuccess (val) {
      this.tagTab[this.currentIndex].configForm = _.cloneDeep(val)
      this.networkPortConfigDialog = false
      this.$emit('operateSuccess')
    },

    /**
     * 关闭网关dialog
     */
    closeNetworkPortDialog () {
      this.networkPortConfigDialog = false
      this.tagTab[this.currentIndex].configForm = _.cloneDeep(this.tagTab[this.currentIndex].configForm)
    },
    /**
     * 关闭设备信息的dialog
     */
    closeBindingEquipmentDialog () {
      this.currentFormData = _.cloneDeep(this.currentForm)
      this.bindingEquipmentDialog = false
    },
    /* 测试连接 */
    async testOnline () {
      onlineTest(this.boxId, this.tagTab[this.currentIndex].configForm.collect_ip).then(res => {
        if (res.data && res.data.result_code === 0) {
          this.$q.loading.show({ message: '正在测试连接，请稍后...' })
          let nowTime = toTime(new Date())
          let space = null
          TestResp(this.boxId).then(res => {
            // const dif = moment(toTime(parseInt(res.data.time) * 1000)).diff(nowTime, 'seconds') + 5
            // if (dif > 0 && res.data.flag) {
            //   this.testResultTip('连接成功')
            // }
          })
          let timeId = setInterval(() => {
            TestResp(this.boxId).then(res => {
              space = moment(toTime(new Date())).diff(nowTime, 'seconds')
              const dif = moment(toTime(parseInt(res.data.time) * 1000)).diff(nowTime, 'seconds') + 5
              if (space > 30) {
                clearInterval(timeId)
                this.$q.loading.hide()
              }
              if (dif > 0 && res.data.flag) {
                this.testResultTip('连接成功')
                clearInterval(timeId)
                this.$q.loading.hide()
                return false
              } else if ((space > 30 || dif > 0) && !res.data.flag) {
                clearInterval(timeId)
                this.testResultTip('连接失败')
                this.$q.loading.hide()
              }
            })
          }, 6000)
        }
      }).finally(() => {
        // this.$q.loading.hide()
      })
    },
    testResultTip (msg) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
                ${msg}</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      })
    }
  }
}
</script>

<style scoped lang="stylus">
.label-width
  width 100px
.info-detail-wrapper
  min-height 500px
  background #ffffff
  border-bottom-left-radius 6px
  border-bottom-right-radius 6px
.info-detail-container
  min-height 500px
  background #ffffff
  border-bottom-left-radius 6px
  border-bottom-right-radius 6px
  padding 20px

  .btn
    padding: 0
    min-width 96px
    min-height 32px
    line-height 1
    width 96px
    height 32px
    border-radius 6px

  .left-container
    padding-top 20px
    padding-right 29px
    border-right 1px solid #D3D3D3
    margin-right 20px
    min-height 460px

  .flex-center
    display flex
    align-items center
    justify-content center

  .center-container
    width 100%
    .select-width
      width 266px
    .info
      margin-top 20px
    .save
      float right
      margin-top 120px
  .config
    margin-top 90px
    display flex
    flex-direction column
  .title
    font-weight 500
    font-size 16px
    color $primary
</style>
